import pydevd_pycharm
import streamlit as st

from llm_chat import llm_response, llm_response_with_weather
from llm_image import llm_image_response
from t_cos import upload_file_to_cos

# 设置页面标题
st.set_page_config(page_title="AI 助手", page_icon="🤖", layout="wide")

# answer = llm_response_with_weather('上海天气怎么样')
# print(answer)
# 设置调试器监听端口
# pydevd_pycharm.settrace('localhost', port=12345, stdoutToServer=True, stderrToServer=True)
# 顶部导航栏
st.title("AI 助手")
st.markdown("一个简单而强大的问答系统和图像识别助手。")

# 侧边栏
with st.sidebar:
    st.header("导航")
    selected_option = st.radio(
        "选择功能",
        ["问答系统", "图像识别"]
    )

# 主内容区
if selected_option == "问答系统":
    st.header("提问")
    question = st.text_input("在这里输入您的问题:")
    if st.button("提交"):
        # 这里将调用大模型API来处理问题
        answer = llm_response_with_weather(question)
        st.write(answer)
        # 暂时将历史记录保存在Session State中
        if 'history' not in st.session_state:
            st.session_state.history = []
        st.session_state.history.append({"type": "QA", "question": question, "answer": answer})

elif selected_option == "图像识别":
    st.header("上传图片")
    uploaded_file = st.file_uploader("选择一张图片...", type=["jpg", "png", "jpeg"])
    if uploaded_file is not None:
        st.image(uploaded_file, caption='已上传的图片', use_column_width=False, width=100)
        # 这里将调用大模型API来处理图片
        file_name = uploaded_file.name
        # 读取文件内容（二进制）
        file_bytes = uploaded_file.getvalue()
        # 如果你需要将文件保存到临时位置并获取路径，可以这样做：
        # 注意：这仅适用于演示目的，实际应用中应避免写入临时文件。

        temp_path = "test.jpg"

        if file_name.endswith("jpg"):
            temp_path = "test.jpg"
        elif file_name.endswith("png"):
            temp_path = "test.png"
        elif file_name.endswith("jpeg"):
            temp_path = "test.jpeg"

        with open(temp_path, 'wb') as f:
            f.write(file_bytes)
        st.write(f"文件已保存到临时路径: {temp_path}")
        st.write(temp_path)

        public_url, signed_url =upload_file_to_cos(temp_path, f"image/{temp_path}")
        if public_url and signed_url:
            print(f"File uploaded successfully.")
            print(f"Public Download URL: {public_url}")
            print(f"Signed Download URL (valid for 1 hour): {signed_url}")
            st.write(public_url)
            st.write(llm_image_response(public_url))
        else:
            print("Failed to upload the file or generate URLs.")

        # 暂时将历史记录保存在Session State中
        if 'history' not in st.session_state:
            st.session_state.history = []
        st.session_state.history.append({"type": "Image", "image": uploaded_file, "result": temp_path})

# 显示历史记录
st.sidebar.header("历史记录")
if 'history' in st.session_state:
    for entry in st.session_state.history:
        if entry["type"] == "QA":
            st.sidebar.write(f"**问:** {entry['question']}")
            st.sidebar.write(f"**答:** {entry['answer']}")
        elif entry["type"] == "Image":
            # 调整图片预览尺寸
            st.sidebar.image(entry['image'], caption='处理过的图片', width=100)  # 可以根据需要调整宽度
            st.sidebar.write(f"**结果:** {entry['result']}")
